package cn.xqj.user.controller;

import cn.xqj.basic.exception.BusinessException;
import cn.xqj.basic.util.AjaxResult;
import cn.xqj.user.dto.BinderDto;
import cn.xqj.user.dto.LoginDto;
import cn.xqj.user.service.ILogininfoService;
import jdk.nashorn.internal.parser.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private ILogininfoService logininfoServiceImpl;


    @PostMapping("/account")
    public AjaxResult loginByAccount(@RequestBody LoginDto loginDto) {
        try {
            Map<String, Object> map = logininfoServiceImpl.loginByAccount(loginDto);
            return AjaxResult.me().setMsg("登录成功！").setResultObj(map);
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg(e.getMessage()).setSuccess(false);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg("服务器繁忙，请稍后再试！").setSuccess(false);
        }

    }



    @GetMapping("/wechat/{code}")
    public AjaxResult loginByWechat(@PathVariable("code") String code) {
        try {
            return logininfoServiceImpl.loginByWechat(code);
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg(e.getMessage()).setSuccess(false);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg("服务器繁忙，请稍后再试！").setSuccess(false);
        }
    }


    @PostMapping("/wechat/binder")
    public AjaxResult wechatBinder(@RequestBody BinderDto binderDto) {
        try {
            return logininfoServiceImpl.wechatBinder(binderDto);
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg(e.getMessage()).setSuccess(false);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg("服务器繁忙，请稍后再试！").setSuccess(false);
        }
    }


    @GetMapping("/logout/{token}")
    public AjaxResult logout(@PathVariable("token") String Token) {

        try {
            logininfoServiceImpl.logout(Token);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("系统繁忙，请稍后再试！");
        }
    }
}
